﻿using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using Xamarin.Auth;
using System;
using Capstone.ViewModels;
using System.Threading;

namespace Capstone.Droid
{
    [Activity(Label = "Darecs", Icon = "@drawable/darecs", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

            global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, savedInstanceState); // Google login

            CustomTabsConfiguration.CustomTabsClosingMessage = null;

            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        public override void OnUserInteraction()
        {
            base.OnUserInteraction();
            if (Xamarin.Forms.Application.Current.Properties.ContainsKey("Access_token"))
            {
                if (DateTime.UtcNow > Convert.ToDateTime(Xamarin.Forms.Application.Current.Properties["Refresh_token_exp"]))
                {
                    AboutViewModel objAboutViewModel = new AboutViewModel();
                    objAboutViewModel.OnLogout();
                }
                else if (DateTime.UtcNow > Convert.ToDateTime(Xamarin.Forms.Application.Current.Properties["Access_token_exp"]))
                {
                    LoginViewModel objLoginViewModel = new LoginViewModel();
                    objLoginViewModel.NewAccessToken();
                }
            }
        }
    }
}